
var hexMD5 = require('./md5.js').hexMD5

var getId = function (len, timestamp) {
  len = len || 32
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length
  var pwd = ''
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}
// 全局参数
var d = {
  id: "",
  encrypt: "md5",
  sign: "",
  client: { caller: "wechat" },
  data: {},
  timestamp: new Date().getTime(),
  format: "json"
}
// 随机数
d.id = getId(10)
// md5加密
var beforeSign = d.id + ':' + "846d2cb0c7f09c3ae802c42169a6302b" + ":" + d.timestamp
var sign = hexMD5(beforeSign)
d.sign = sign
console.log('公用参数', d)

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

var Config = require('../config/index.js')
var md5 = hexMD5

function wxPromisify(fn) {
  return function (obj = {}) {
    obj.url = Config.postUrl + obj.url
    if (obj.isLoading) {
      wx.showLoading({
        title: obj.loadingText || '请求中...',
      })
    }

    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res.data)
      }

      obj.fail = function (res) {
        console.log('接口请求错误', res)
        reject(res.data)
      }

      obj.complete = function (res) {
        console.log('接口请求完成', res)
        if (obj.isLoading) {
          wx.hideLoading()
        }
      }

      fn(obj)
    })
  }
}

function getId(len, timestamp) {
  len = len || 32
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length
  var pwd = ''
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

function getGlobalParam() {
  // 全局参数
  var d = {
    id: getId(10),
    encrypt: "md5",
    sign: "",
    client: { caller: "wechat" },
    data: {},
    timestamp: new Date().getTime(),
    format: "json",
    user: wx.getStorageSync('userInfo') || {},
    userCode: 'ce5beeca-32d5-4673-be39-a001fe95e04b',
    appId: Config.appid
  }
  d.user = wx.getStorageSync('userInfo') || {}
  // md5加密
  var beforeSign = d.id + ':' + "846d2cb0c7f09c3ae802c42169a6302b" + ":" + d.timestamp
  var sign = md5(beforeSign)
  d.sign = sign

  return d
}

function paySign(data) {
  var ss = 'appId=' + Config.appid + '&nonceStr=' + data.nonceStr + '&package=prepay_id=' + data.prepayId + '&signType=MD5&timeStamp=' + data.timeStamp + '&key=' + Config.key
  return md5(ss)
}

//创建文件夹名字
function makeFolderName(folderName = 'image') {
  var now = new Date();
  var nowYear = now.getFullYear();
  var nowMonth = now.getMonth() + 1;
  if (nowMonth < 10) {
    nowMonth = '0' + nowMonth;
  } else {
    nowMonth = String(nowMonth);
  }
  return '/' + folderName + '/' + nowYear + '-' + nowMonth + '/';
}

//创建文件名字
function makeFileName(suffix = '', prefix = '') {
  var guid = "";
  for (var i = 1; i <= 32; i++) {
    var n = Math.floor(Math.random() * 16.0).toString(16);
    guid += n;
    if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
      guid += "-";
  }
  return prefix + guid + suffix;
}

//转换rpx到px
function rpx2px(rpx) {
  return rpx / getApp().globalData.sysInfo.rpxRatio
}

//转换px到rpx
function px2rpx(px) {
  return px * getApp().globalData.sysInfo.rpxRatio
}

function checkStatus(res, _this) {
  if (!res) {
    return false
  }
  if (res.state.code == 0) {
    return true
  } else {
    _this.setData({
      isOpen: true,
      msg: res.state.msg
    })
    return false
  }
}

module.exports = {
  formatTime: formatTime,
  wxPromisify: wxPromisify,
  getId: getId,
  getGlobalParam: getGlobalParam,
  paySign: paySign,
  makeFolderName: makeFolderName,
  makeFileName: makeFileName,
  rpx2px: rpx2px,
  px2rpx: px2rpx,
  checkStatus: checkStatus,
  initData: d 
}